﻿using System.Configuration;

namespace PMIS.Common
{
    public class AppSettingsHelper
    {
        // 获取配置项值
        public static T GetValue<T>(string key, T defaultValue)
        {
            var value = ConfigurationManager.AppSettings[key];
            if (value == null)
                return defaultValue;

            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }

        // 设置配置项值
        public static void SetValue(string key, string value)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            if (settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }

            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
        }

        #region 配置文件中的配置属性

        /// <summary>
        /// 是否记住我
        /// </summary>
        public static bool IsRemberMe
        {
            get => GetValue(nameof(IsRemberMe), false);
            set => SetValue(nameof(IsRemberMe), value.ToString());
        }

        /// <summary>
        /// 上次登录账号
        /// </summary>
        public static string UserName
        {
            get => GetValue(nameof(UserName), "");
            set => SetValue(nameof(UserName), value);
        }

        /// <summary>
        /// 上次登录密码
        /// </summary>
        public static string Password
        {
            get => GetValue(nameof(Password), "");
            set => SetValue(nameof(Password), value);
        }

        #endregion
    }
}
